package com.teach.servlet.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * <pre>
 * -
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Tel : 151 1104 7708
 * Date : 2022-05-10 10:32
 * Version : 1.0
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 **/
@WebServlet("/demo/down.let")
public class DownServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String uri = req.getParameter("file");
    File file = new File(UploadServlet.root,uri);
    if(!file.isFile()){
      resp.sendError(404, "文件没找到");
      return;
    }
    resp.reset();
//    resp.setContentType("application/stream");
//    resp.setContentType("image/png");
//    String fileName = "要下载的文件名.png";
//    resp.setHeader("Content-Length", file.length()+"");
//    resp.setHeader("Content-disposition","attachment;filename=\""+new String(fileName.getBytes(),"ISO-8859-1")+"\"");//下载的文件名
    try(
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();
        ){
      int len = 0;
      byte[] bs = new byte[1024];
      while((len=in.read(bs))>0){
        out.write(bs, 0, len);
      }
    }
  }
}
